package cn.rtangyy.seckilling.rabbitmq;

import cn.rtangyy.seckilling.entity.SeckillMessage;
import cn.rtangyy.seckilling.entity.SeckillOrder;
import cn.rtangyy.seckilling.entity.User;
import cn.rtangyy.seckilling.service.GoodsService;
import cn.rtangyy.seckilling.service.OrderService;
import cn.rtangyy.seckilling.utils.JsonUtil;
import cn.rtangyy.seckilling.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MQReceiver {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    /**
     * 下单操作
     */
    @RabbitListener(queues = "seckillQueue")
    public void receive(String msg) {
        log.info("接收的消息：" + msg);
        SeckillMessage seckillMessage = JsonUtil.jsonString2Object(msg, SeckillMessage.class);
        Long goodsId = seckillMessage.getGoodsId();
        User user = seckillMessage.getUser();
        // 判断库存
        GoodsVo goodsVo = goodsService.findGoodsVoById(seckillMessage.getGoodsId());
        if (goodsVo.getStockCount() < 1) {
            return;
        }
        // 在 Redis 中存储订单消息，判断是否重复抢购
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if (null != seckillOrder) {
            return ;
        }
        // 下单操作
        orderService.seckill(user,goodsVo);

    }

}
